<template>
  <div>

    <el-card>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-input placeholder="图书编号" v-model="searchForm.isbn"></el-input>
        </el-col>
        <el-col :span="5">
          <el-input placeholder="书名" v-model="searchForm.name"></el-input>
        </el-col>
        <el-col :span="5">
          <el-select v-model="searchForm.typeId" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="success" icon="el-icon-search" @click="handleSearchLibrary" plain>搜索</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="warning" icon="el-icon-refresh-left" @click="handleResetLibrary" plain>重置</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" icon="el-icon-plus" @click="addLibrary" plain>添加</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteLibrary" plain>删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-row>
        <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              align="center"
              prop="picture"
              label="图片"
              width="200">
            <template slot-scope="scope">
              <img :src="scope.row.picture" style="width: 140px;height: 140px;">
            </template>
          </el-table-column>
          <el-table-column
              prop="isbn"
              label="图书编号"
              width="120">
          </el-table-column>
          <el-table-column
              prop="name"
              label="图书名称"
              width="120">
          </el-table-column>
          <el-table-column
              prop="typeId"
              label="图书类型"
              width="120">
            <template slot-scope="scope">
              {{ typeNamesMap[scope.row.typeId] }}
            </template>
          </el-table-column>
          <el-table-column
              prop="author"
              label="作者"
              width="120">
          </el-table-column>
          <el-table-column
              prop="price"
              label="价格"
              width="120">
          </el-table-column>
          <el-table-column
              prop="language"
              label="语言"
              width="120">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="145"
              header-align="center">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center;">
              <el-button @click="updateLibrary(scope.row)" type="primary" plain icon="el-icon-edit" circle size="small"></el-button>
              <el-button type="danger" plain icon="el-icon-delete" circle size="small" @click="deleteLibrary(scope.row)"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">

      <el-form :model="libraryForm" :rules="rules" ref="libraryForm">

        <el-form-item label="图书图片" :label-width="formLabelWidth" prop="picture">
          <el-upload
              class="avatar-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="changePicture"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="图书名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="libraryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书编号" :label-width="formLabelWidth" prop="isbn">
          <el-input v-model="libraryForm.isbn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书类别" :label-width="formLabelWidth" prop="typeId">
          <el-select v-model="libraryForm.typeId" placeholder="请选择" style="width: 100%;">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图书作者" :label-width="formLabelWidth" prop="author">
          <el-input v-model="libraryForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书出版社" :label-width="formLabelWidth" prop="publish">
          <el-input v-model="libraryForm.publish" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书语言" :label-width="formLabelWidth" prop="language">
          <el-input v-model="libraryForm.language" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图书价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="libraryForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" :label-width="formLabelWidth" prop="publishDate">
          <el-date-picker
              v-model="libraryForm.publishDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图书介绍" :label-width="formLabelWidth" prop="introduction">
          <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入图书简介"
              v-model="libraryForm.introduction"
              autocomplete="off">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" plain @click="subForm">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "LibraryViews",
  data() {
    return {
      dialogTitle: '',
      formData: new FormData(),
      imageUrl: '',
      formLabelWidth: '100px',
      dialogVisible: false,
      options: [],
      libraryForm: {
        name: '',
        author: '',
        publish: '',
        isbn: '',
        introduction: '',
        language: '',
        price: '',
        publishDate: '',
        typeId: '',
        status: 0,
        picture: '',
      },
      tableData: [],
      pageData:{
        currentPage:1,
        pageSize:5,
        total:0
      },
      searchForm:{
        isbn: '',
        name:'',
        typeId:''
      },
      bookList: [],
      typeNamesMap: {},
      rules: {
        name: [
          { required: true, message: '请输入图书名称', trigger: 'blur' },
        ],
        isbn: [
          { required: true, message: '请输入图书编号', trigger: 'blur' },
        ],
        typeId: [
          { required: true, message: '请选择图书类别', trigger: 'blur' },
        ],
        author: [
          { required: true, message: '请输入图书作者', trigger: 'blur' },
        ],
        publish: [
          { required: true, message: '请输入图书出版社', trigger: 'blur' },
        ],
        language: [
          { required: true, message: '请输入图书语言', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入图书价格', trigger: 'blur' },
        ],
        publishDate: [
          { required: true, message: '请选择出版日期', trigger: 'blur' },
        ],
        introduction: [
          { required: true, message: '请输入图书简介', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getLibraryList()
    this.fetchTypeNames()
  },
  methods:{
    resetForm() {
      this.libraryForm = {
        name: '',
        author: '',
        publish: '',
        isbn: '',
        introduction: '',
        language: '',
        price: '',
        publishDate: '',
        typeId: '',
        status: '',
        picture: '',
        id: ''
      };
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getLibraryList()
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getLibraryList()
    },
    handleSearchLibrary() {
      this.pageData.currentPage = 1; // 搜索时重置页码
      this.getLibraryList();
    },
    handleResetLibrary() {
      this.searchForm.isbn = '';
      this.searchForm.name = '';
      this.searchForm.typeId = '';
      this.pageData.currentPage = 1; // 重置页码
      this.getLibraryList()
    },
    async getLibraryList() {
      const params = { ...this.pageData, ...this.searchForm };
      try {
        const { data: res } = await this.$axios.get("bookInfo/getBookInfo", { params });
        if (res && res.data) {
          this.tableData = res.data.records || [];
          this.pageData.total = res.data.total || 0;
        } else {
          this.tableData = [];
          this.pageData.total = 0;
        }
      } catch (error) {
        console.error('获取图书列表失败:', error);
        this.tableData = [];
        this.pageData.total = 0;
      }
    },
    async fetchTypeNames() {
      const { data: res } = await this.$axios.get("typeInfo/getAllTypeNames");
      this.options = res.data.map(type => ({
        value: type.id,
        label: type.name
      }));
      this.typeNamesMap = res.data.reduce((map, type) => {
        map[type.id] = type.name;
        return map;
      }, {});
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm(); // 重置表单数据
            this.imageUrl = '';
            this.formData = new FormData();
            this.libraryForm = {
              name: '',
              author: '',
              publish: '',
              isbn: '',
              introduction: '',
              language: '',
              price: '',
              publishDate: '',
              typeId: '',
              status: '',
            }
            done();
          })
          .catch(_ => {});
    },
    subForm() {
      this.$refs.libraryForm.validate(async valid => {
        if (valid) {
          for (let key in this.libraryForm){
            if (key === 'publishDate') {
              // 将 publishDate 转换为 Date 对象
              this.formData.append(key, new Date(this.libraryForm[key]));
            } else {
              this.formData.append(key, this.libraryForm[key]);
            }
          }
          const { data: res} = await this.$axios.post("bookInfo/addOrUpdate", this.formData);
          if (res.data) {
            this.$message.success('操作成功');
            this.dialogVisible = false;
            await this.getLibraryList();
            this.resetForm();
            this.imageUrl = '';
            this.formData = new FormData();
            this.libraryForm = {
              name: '',
              author: '',
              publish: '',
              isbn: '',
              introduction: '',
              language: '',
              price: '',
              publishDate: '',
              typeId: '',
              status: '',
            }
          } else {
            this.$message.error('操作失败');
            return false;
          }
        }
      });
    },
    updateLibrary(row){
      this.libraryForm = row
      this.imageUrl = row.picture
      this.dialogVisible = true
      this.dialogTitle = "修改图书"
    },
    addLibrary(){
      this.dialogVisible = true
      this.dialogTitle = "添加图书"
    },
    deleteLibrary(row){
      this.$confirm('此操作将永久删除该图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("bookInfo/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getLibraryList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteLibrary() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的图书');
        return;
      }
      this.$confirm('此操作将永久删除选中的图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("bookInfo/batchDeleteBookInfo", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getLibraryList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changePicture(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if (this.imageUrl){
      this.formData.append('file', file.raw);
      }
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
    cancelDialog() {
      this.resetForm();
      this.$refs.libraryForm.clearValidate();
      this.imageUrl = '';
      this.dialogVisible = false;
      this.formData = new FormData();
      this.libraryForm = {
        name: '',
        author: '',
        publish: '',
        isbn: '',
        introduction: '',
        language: '',
        price: '',
        publishDate: '',
        typeId: '',
        status: '',
      }
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>